#!/bin/bash

if [ -z "$1" ]; then
    echo "[usage] $0 {safe | sade | sim | ufs64sim} [<sub_dir>]"
    exit 1
fi

target=$1
sub=$2

proot=`accurev info 2>&1| grep Top | awk '{print $2}'`
if [ -z "$proot" ]; then
    proot=`git rev-parse --show-toplevel 2>&1`
    if [ $? != 0 ]; then 
        echo "ERROR: not in either accurev or git workspace"
        exit 1
    fi
fi

export CFG_FLAVOR=DEBUG

if [ "$target" == "sim" ]; then
    target="safe"
    sub="layered/MLU/krnl/cbfs_driver"
fi


if [ "$target" == "ufs64sim" ]; then
    target="safe"
    sub="layered/MLU/test/MUT/ufs64"
fi

if [ -z "$sub" ]; then
    if [ "$target" == "safe" ]; then
        sub="layered/MLU"
    fi
    if [ "$target" == "sade" ]; then
        sub="Dart"
    fi
fi

declare required
if [ -e "$proot/build/tags/KHDATAPATH" ]; then
    required=`grep SLES $proot/build/tags/KHDATAPATH | awk '{print $2}'`
fi
echo "Required Build ENV: $required"

declare present
if [ -e "/etc/c4buildversion" ]; then
    present=`cat /etc/c4buildversion | awk '{print $1}'`
fi
echo "Present Build ENV: $present"

if [ -n "$required" ] && [ -n "$present" ] && [ "$required" != "$present" ]; then 
    echo "Switch to Build ENV: $required"
    (gosp1 --dist $required -- $proot --- -c "cd $proot/$target && ./build.sh -t GNOSIS -f DEBUG --subdir $sub --build-only --no-package") 2>&1 | tee $proot/partialmake.log
else
    (cd $proot/$target && ./build.sh -t GNOSIS -f DEBUG --subdir $sub --build-only --no-package) 2>&1 | tee $proot/partialmake.log
fi
